package com.zhou.bjgl.bjgl.exception;


import com.zhou.bjgl.bjgl.resp.common.ApiRestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/*
* 统一异常提示
* */
@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger logger=LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e){
        e.printStackTrace();
        logger.error("Default Exception:",e);
        return ApiRestResponse.error(BwExceptionEnum.SYSTEM_EXCEPTION);
    }

    @ResponseBody
    @ExceptionHandler(BwException.class)
    public Object HandleImoocMallException(BwException e){
        e.printStackTrace();
        logger.error("ImoocMallException:",e);
        return ApiRestResponse.error(e.getCode(),e.getMsg());
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiRestResponse handleMethodArgumentNotValidException(
            MethodArgumentNotValidException e) {
        e.printStackTrace();
        logger.error("MethodArgumentNotValidException",e);
        return handleBindingResult(e.getBindingResult());
    }

    private ApiRestResponse handleBindingResult(BindingResult result){
        //把异常处理为对外暴露的提示
        List<String> list=new ArrayList<>();
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError objectError:
                 allErrors) {
                String message = objectError.getDefaultMessage();
                list.add(message);

            }
        }
        if (list.size()==0){
            return ApiRestResponse.error(BwExceptionEnum.REQUEST_PARAM_ERROR);
        }
        return ApiRestResponse.error(BwExceptionEnum.REQUEST_PARAM_ERROR.getCode(),list.toString());
    }

}
